<template>
  <div class="dashboard-container">
    <el-button class="add-btn" type="primary" size="default" @click="handleAddVillage">新增乡村</el-button>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column fixed type="index" label="序号" width="120" />
      <el-table-column prop="villageName" label="乡村名称" />
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button type="primary" @click="handleUpdate(scope.row)">修改</el-button>
          <el-popconfirm title="确定删除?" @confirm="handleDelete(scope.row)">
            <template #reference>
              <el-button type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <VillageDialog v-if="dialogVisible" v-model:visible="dialogVisible" :village="cVillage" @refresh="getVillageList" />
  </div>
</template>

<script lang="ts" name="Village" setup>
import { deleteVillage, villageList } from '@/api/village'
import type { VillageInfo } from '@/api/village.model'
import useErrorMessage from '@/hooks/useErrorMessage'
import { ElMessage } from 'element-plus'

const tableData = ref<VillageInfo[]>([])
const cVillage = ref<VillageInfo | {}>({})
const dialogVisible = ref<boolean>(false)

onMounted(() => {
  getVillageList()
})

const getVillageList = async () => {
  try {
    const { data } = await villageList()
    tableData.value = data.data
  } catch (error) {
    useErrorMessage(error)
  }
}

const handleAddVillage = () => {
  cVillage.value = {}
  dialogVisible.value = true
}

const handleUpdate = (row: VillageInfo) => {
  cVillage.value = row
  dialogVisible.value = true
}

const handleDelete = async (row: VillageInfo) => {
  try {
    await deleteVillage(row.villageId as number)
    ElMessage.success('删除成功')
    getVillageList()
  } catch (error) {
    useErrorMessage(error)
  }
}
</script>

<style scoped lang="scss">
@import '@/styles/variables.scss';

.dashboard-container {
  padding: 15px;
  color: $color-primary;
  .add-btn {
    float: right;
  }
}
</style>
